<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\middleware\Auth;
use app\BaseController;
use think\facade\View;
use app\common\model\Admin as AdminModel;
use app\common\validate\Admin as AdminValidate;
use think\exception\ValidateException;

class Admin extends BaseController
{
    protected $failException = true;
    protected $middleware = [
        Auth::class
    ];
    
    public function index()
    {
        $nav_title = [
            'nav_title' => '管理员管理',
            'title' => '管理员列表'
        ];

        // 接收查询字段
        $SearchField = $this->request->param('search_field','username');

        $keyword = $this->request->param('keyword','');

        $where = [];

        if(!empty($SearchField) && !empty($keyword))
        {
            $where[] = [$SearchField,'like',"%$keyword%"];
        }else{
            $keyword = '请输入相应的内容';
        }

        // 查询数据
        $AdminList = AdminModel::where($where)->paginate(['list_rows' => 10,'query' => request()->param()]);

        return View::fetch('',[
            'nav_title' => $nav_title,
            'AdminList' => $AdminList,
            'SearchField' => $SearchField,
            'keyword' => $keyword
        ]);
    }

    public function add()
    {
        if($this->request->isPost())
        {
            // 接收所有的参数
            $params = $this->request->param();

            // 生成密码盐
            $salt = build_ranstr();

            // 封装数据
            $data = [
                'username' => $params['username'],
                'nickname' => $params['nickname'],
                'password' => $params['password'],
                'salt' => $salt,
                'state' => $params['state']
            ];

            // 验证数据
            try {
                validate(AdminValidate::class)->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getError());
            }


            if($params['password'] != $params['repass'])
            {
                $this->error('密码与确认密码不一致');
            }

            // 密码进行加密
            $data['password'] = md5($params['password'].$salt);

            // 实例化模型
            $AdminModel = new AdminModel();

            // 插入数据库
            $result = $AdminModel->save($data);

            if($result !== true)
            {
                $this->error('新增失败');
                
            }else{
                $this->success('新增成功',(String)url('admin/admin/index'));
                
            }
        }

        $nav_title = [
            'nav_title' => '管理员管理',
            'title' => '新增管理员'
        ];

        return View::fetch('',[
            'nav_title' => $nav_title,
        ]);
    }

    public function edit()
    {
        // 接收到管理员id
        $adminid = $this->request->param('adminid',0);

        $admin = AdminModel::find($adminid);
        
        if(!$admin)
        {
           $this->error('所选的管理员不存在，请重新选择');
            
        }

        if($this->request->isPost())
        {
            // 接收表单提交的数据
            $params = $this->request->param();

            // 封装数据数组
            $data = [
                'username' => $params['username'],
                'nickname' => $params['nickname'],
                'state' => $params['state']
            ];

            if($params['password'])
            {
                if(md5($params['oldpass'].$admin['salt']) != $admin['password'])
                {
                    $this->error('密码与确认密码不一致');
                }

                if($params['password'] != $params['repass'])
                {
                    $this->error('密码与确认密码不一致');
                }

                $salt = build_ranstr();

                $data['salt'] = $salt;

                $data['password'] = md5($params['password'].$salt);
            }

            $result = $admin->save($data);

            if($result !== true)
            {
                $this->error('编辑失败');
                
            }else{
                if(!empty($data['password']) && $adminid == $this->request->LoginAdmin['id'])
                {
                    cookie('LoginAdmin',null);
                    $this->success('编辑成功',(String)url('admin/index/login'));
                }

                $this->success('编辑成功',(String)url('admin/admin/index'));
                
            }
        }

        $nav_title = [
            'nav_title' => '管理员管理',
            'title' => '编辑管理员'
        ];
        return View::fetch('',[
            'nav_title' => $nav_title,
            'admin' => $admin
        ]);
    }

    public function del()
    {
        if($this->request->isAjax())
        {
            $adminid = $this->request->param('adminid');

            if(empty($adminid))
            {
                $this->error('请选择要删除的管理员');
            }

            if(is_array($adminid))
            {
                // 批量删除操作

                // 查询数据
                $idArr = AdminModel::whereIn('id',$adminid)->column('id');

                $NotId = '';
                
                foreach ($adminid as $item) {
                    if(!in_array($item,$idArr))
                    {
                        $NotId .= $item . ',';
                    }
                }
                
                if(!empty($NotId))
                {
                    $NotId = rtrim($NotId,',');
                    $this->error("ID：{$NotId}不存在，请重新选择");
                }

                if(in_array($this->request->LoginAdmin['id'],$idArr))
                {
                    $this->error("不能选中当前登录的用户ID:{$this->request->LoginAdmin['id']}，请重新选择");
                }

                $result = AdminModel::destroy($adminid);

                if($result !== true)
                {
                    $this->error('批量删除失败');
                }else{
                    $this->success('批量删除成功');
                }


            }else{
                // 单条删除

                $admin = AdminModel::find($adminid);

                if(!$admin)
                {
                    $this->error('该管理员不存在，请重新选择');
                }

                if($admin['id'] == $this->request->LoginAdmin['id'])
                {
                    $this->error('不能删除当前登录的管理员');
                }

                $result = AdminModel::destroy($adminid);

                if($result !== true)
                {
                    $this->error('删除失败');
                }else{
                    $this->success('删除成功');
                }

            }
        }
    }

    public function state()
    {
        if($this->request->isAjax())
        {
            $state = $this->request->param('state');

            $adminid = $this->request->param('adminid',[]);

            // 查询数据
            $AdminList = AdminModel::whereIn('id',$adminid)->column('id,state');

            // 存在查询出来的id数组
            $IdList = [];


            if(!$adminid)
            {
                $this->error('没有选择到管理员');
            }

            foreach($AdminList as $item)
            {
                $IdList[] = $item['id'];
            }

            // 存放不存在的id
            $NotStateId = '';

            foreach($adminid as $item)
            {
                if(!in_array($item,$IdList))
                {
                    $NotStateId .= $item . ',';
                }
            }

            // 提示
            if(!empty($NotStateId))
            {
                $NotStateId = rtrim($NotStateId,',');

                $this->error("ID：{$NotStateId}不存在，请重新选择");
            }
            
            $AdminModel = new AdminModel();

            // 如果state变量是为true，那么就是启用操作
            if($state)
            {
                // 启用操作

                // 判断选中的数据是否存在已启用的
                foreach ($AdminList as $item) {
                    if($item['state'] == 1)
                    {
                        $this->error('存在已启用的管理员,请重新选择');
                    }
                }

                // 更新数组
                $data = [];

                foreach($adminid as $item)
                {
                    if(in_array($item,$IdList))
                    {
                        $data[] = [
                            'id' => $item,
                            'state' => 1
                        ];
                    }
                }

                
                $result = $AdminModel->saveAll($data);

                if($result)
                {
                    $this->success('启用成功');
                }else{
                    $this->error('启用失败');
                }


            }else{
                // 禁用操作
                
                // 是否选中当前的登录管理员
                if(in_array($this->request->LoginAdmin['id'],$IdList))
                {
                    $this->error('不能禁用当前登录管理员');
                }

                // 判断选中的数据是否存在已启用的
                foreach ($AdminList as $item) {
                    if($item['state'] == 0)
                    {
                        $this->error('存在已禁用的管理员,请重新选择');
                    }
                }

                // 更新数组
                $data = [];

                foreach($adminid as $item)
                {
                    if(in_array($item,$IdList))
                    {
                        $data[] = [
                            'id' => $item,
                            'state' => 0
                        ];
                    }
                }

                $result = $AdminModel->saveAll($data);

                if($result)
                {
                    $this->success('禁用成功');
                }else{
                    $this->error('禁用失败');
                }
            }
        }
    }
}
